#pragma once

#include "Task.hpp"
#include <iostream>
#include <queue>
#include <pthread.h>
#include <unistd.h>


template <class T>
class BlockQueue
{
    static const int defaultnum = 20;

public:
    BlockQueue(int maxcap = defaultnum) : _maxcap(maxcap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        //_low_water=defaultnum/3;
        //_high_water=(defaultnum*2)/3;
    }
    // 生产
    const T &push(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        while (_maxcap == _queue.size()) {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        _queue.push(in);
        //if(_queue.size()>_high_water) pthread_cond_signal(&_c_cond);
        pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);
    }
    // 消费
    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_queue.size() == 0) {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        T out = _queue.front();
        _queue.pop();
        //if(_queue.size()<_low_water) pthread_cond_signal(&_p_cond);
        pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);
        return out;
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    std::queue<T> _queue; // 临界资源
    int _maxcap;          // 队列极值
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;
    //int _low_water;
    //int _high_water;
};
